package com.wxdc.nmgyt.nmgytwydc.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.wxdc.nmgyt.nmgytwydc.R;
import com.wxdc.nmgyt.nmgytwydc.adapter.AuditBackData_RecyclerviewAdapter;
import com.wxdc.nmgyt.nmgytwydc.greendao.ope.JcdInfoBeanDaoOpe;
import com.wxdc.nmgyt.nmgytwydc.model.BASE_WORKFLOWCURRENT;
import com.wxdc.nmgyt.nmgytwydc.model.COMMIT_AUDIT;
import com.wxdc.nmgyt.nmgytwydc.model.JcdInfoBean;
import com.wxdc.nmgyt.nmgytwydc.model.backresult.AuditResultBean;
import com.wxdc.nmgyt.nmgytwydc.model.backresult.AuditRolResultBean;
import com.wxdc.nmgyt.nmgytwydc.model.backresult.ValidateJcdInfoResultBean;
import com.wxdc.nmgyt.nmgytwydc.presenter.AuditPersenter;
import com.wxdc.nmgyt.nmgytwydc.presenter.contract.AuditContract;
import com.wxdc.nmgyt.nmgytwydc.utils.Network;
import com.wxdc.nmgyt.nmgytwydc.utils.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by Administrator on 2018/11/28.
 * 审核回退数据
 */

public class AuditBackDataActivity extends BaseActivity<AuditPersenter> implements AuditContract.View,SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.toolbar_title)
    TextView mToolbarTitle;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.audit_backdata_recyclerview)
    RecyclerView mAuditBackdataRecyclerview;
    @BindView(R.id.audit_backdata_srlayout)
    SwipeRefreshLayout mAuditBackdataSrlayout;
    private AuditBackData_RecyclerviewAdapter mViewAdapter;
    private List<BASE_WORKFLOWCURRENT> backDatas;//回退数据
    @Override
    protected int getLayout() {
        return R.layout.activity_auditbackdata;
    }

    @Override
    protected void initInject() {
        getActivityComponent().Inject(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setSupportActionBar(mToolbar);
        mToolbarTitle.setText(getResources().getString(R.string.manager_02));
        ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeButtonEnabled(true);
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setTitle("");
        //设置RecyclerView
        mAuditBackdataRecyclerview.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        //设置SwipeRefreshLayout
        mAuditBackdataSrlayout.setOnRefreshListener(this);
        mAuditBackdataSrlayout.setColorSchemeColors(getResources().getColor(R.color.paleturquoise));
        //解决swipelayout与Recyclerview的冲突
        mAuditBackdataRecyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                //计算Recyclerview第一个item的位置是否可见
                int topRowVerticalPosition = (recyclerView == null || recyclerView.getChildCount() == 0) ? 0 : recyclerView.getChildAt(0).getTop();
                // Log.i(TAG, "onScrollStateChanged: -----------" + topRowVerticalPosition +"----------"+recyclerView.getChildCount()+"---------"+recyclerView.getChildAt(0).getTop());
                //当第一个item不可见时，设置SwipeRefreshLayout不可用
                mAuditBackdataSrlayout.setClickable(topRowVerticalPosition == 0);
            }
        });
       backDatas = new ArrayList<>();
       requestBackDataFun();
    }

    /**
     * 更新recyclerview
     */
    private BASE_WORKFLOWCURRENT backDataobj;
    private void updateUI(){
        if (mViewAdapter == null) {
            // Log.i(TAG, "updateJcdInfoUI: ---------------if");
            mViewAdapter = new AuditBackData_RecyclerviewAdapter(mContext, backDatas);
            mAuditBackdataRecyclerview.addItemDecoration(new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL));//添加默认分割线
            mAuditBackdataRecyclerview.setAdapter(mViewAdapter);
            mViewAdapter.setItemClickListener(new AuditBackData_RecyclerviewAdapter.RecyclerViewOnItemClickListener() {
                @Override
                public void onItemClick(View v) {//点击事件显示回退意见信息
                    int position = (int) v.getTag();
                    backDataobj = backDatas.get(position);
                    switch (v.getId()) {
                        case R.id.ad_rv_item_commit_txt:
                            //mApp.showToastLongMessage(mContext,"提交审核");
                            commitAuditFun();
                            break;
                        default:
                            showCommentDialog(backDataobj);
                            break;
                    }
                }
            });
            //长按事件
            mViewAdapter.setItemLongClickListener(new AuditBackData_RecyclerviewAdapter.RecyclerViewOnLongClickListener() {
                @Override
                public void onLongClick(int position) {
                    JcdInfoBean infoBean = JcdInfoBeanDaoOpe.queryForUseridAndYdName(mContext, SharedPreferenceUtil.getGzdwdm(), backDatas.get(position).getGEMNAME());
                    if (infoBean != null) {
                        EventBus.getDefault().postSticky(infoBean);
                        WebActivity.start(mContext, "file:///android_asset/MobileT_Yd.html", "ydinfo");
                    }
                }
            });
        } else {
            mViewAdapter.notifyDataSetChanged();
            //   Log.i(TAG, "updateJcdInfoUI: -----------else");
        }
        mAuditBackdataSrlayout.setRefreshing(false);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int selectId = item.getItemId();
        switch (selectId) {
            case android.R.id.home:
                this.finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 提交审核
     * @param obj
     */
    private AlertDialog commitDialog;
    private void commitAuditFun(){
        commitDialog = new AlertDialog.Builder(mContext)
                .setMessage("("+backDataobj.getGEMNAME()+")是否提交审核？")
                .setNegativeButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (commitDialog != null) {
                            commitDialog.dismiss();
                        }
                    }
                })
                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (commitDialog != null) {
                            commitDialog.dismiss();
                        }
                        if (!Network.isConnected(mContext)) {
                            mApp.showToastLongMessage(mContext, getResources().getString(R.string.no_network));
                            return;
                        }
                        mCircleProgressDialog.showDialog();
                        mPersenter.getUserAuditRol();//获得权限
                    }
                }).create();
        commitDialog.show();
    }
    /**
     * 向服务器请求回退数据
     */
    private void requestBackDataFun(){
        if (!Network.isConnected(mContext)) {
            mApp.showToastLongMessage(mContext, getResources().getString(R.string.no_network));
            mAuditBackdataSrlayout.setRefreshing(false);
            return;
        }
        mPersenter.findAuditData(0);
    }
    /**
     * 实现SwipeRefreshLayout.OnRefreshListener事件的onRefresh方法
     *   下拉刷新
     */
    @Override
    public void onRefresh() {
       requestBackDataFun();
    }
    @Override
    public void showError(String msg) {
        if (mAuditBackdataSrlayout != null) {
            mAuditBackdataSrlayout.setRefreshing(false);
        }
        hideProgressDialog();
    }

    //打开当前页面
    public static void startActivity(Context context) {
        Intent intent = new Intent(context, AuditBackDataActivity.class);
        context.startActivity(intent);
    }

    /**
     * 获取当前用户的审核权限
     * @param resultBeans
     */
    @Override
    public void userAuditRolResult(List<AuditRolResultBean> resultBeans) {
        if (resultBeans != null) {
            int len = resultBeans.size();
            for (int i = 0 ; i < len ; i++) {
                if (resultBeans.get(i).getAUDITSTATEDM().equals("1003")) {
                    COMMIT_AUDIT commit_audit = new COMMIT_AUDIT();
                    commit_audit.setWFSTATE("1");
                    commit_audit.setGEMPOINTID(backDataobj.getGEMPOINTID());
                    commit_audit.setSAMPLEPLOTID(backDataobj.getSAMPLEPLOTID());
                    commit_audit.setGEMNAME(backDataobj.getGEMNAME());
                    commit_audit.setAUDITROLEID(resultBeans.get(i).getAUDITRANKDM());
                    commit_audit.setAUDITSTATEDM(resultBeans.get(i).getAUDITSTATEDM());
                    commit_audit.setAUDITSTATE(resultBeans.get(i).getAUDITSTATENAME());
                    commit_audit.setAUDITIDEA("");
                    commit_audit.setAUDITFEILD("");
                    commit_audit.setFLOWNODEID(backDataobj.getFLOWNODEID());
                    commit_audit.setVERSION(backDataobj.getVERSION());
                    mPersenter.commitAudit(commit_audit);//向服务器提交审核
                }
            }
        }
    }

    /**
     * CurrentReview/2    审核数据
     * @param results
     */
    @Override
    public void getAuditDataResult(List<BASE_WORKFLOWCURRENT> results) {

    }

    /**
     * 待审和退回数据
     * @param results
     */
    @Override
    public void getBackOrWaitAuditDataResult(List<BASE_WORKFLOWCURRENT> results) {
        backDatas.clear();
        if (results != null) {
            int len = results.size();
            for (int i = 0 ; i < len; i++) {
                if (results.get(i).getAUDITSTATEDM().equals("1002")) {
                    backDatas.add(results.get(i));
                }
            }
        }
        updateUI();
    }

    /**
     * 提交审核返回结果
     * @param resultBean
     */
    @Override
    public void getCommitAuditResult(AuditResultBean resultBean) {
        mCircleProgressDialog.dismiss();
        if ("200".equals(resultBean.getCode()) && resultBean.getUs().equals("0")) {
            mApp.showToastLongMessage(mContext,resultBean.getReMessage());
            mPersenter.findAuditData(0);
        }
    }

    @Override
    public void getYdInfoValidateResult(ValidateJcdInfoResultBean obj) {

    }

    /**
     * 显示回退意见对话框
     * @param obj
     */
    private AlertDialog commentDialog;
    private void showCommentDialog(BASE_WORKFLOWCURRENT obj) {
        View dialogV = getLayoutInflater().inflate(R.layout.dialog_backcomment_item, null);
        TextView title_v = dialogV.findViewById(R.id.dialog_backcomment_item_title);
        TextView content_v = dialogV.findViewById(R.id.dialog_backcomment_item_content);
         title_v.setText(obj.getGEMNAME()+"(回退意见)");
         content_v.setText(obj.getAUDITIDEA());
        commentDialog = new AlertDialog.Builder(mContext)
                .setView(dialogV)
                .setPositiveButton("返回", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        if (commentDialog != null) {
                            commentDialog.dismiss();
                        }
                    }
                }).create();
        commentDialog.show();
    }
    //-------------------------------------------------------------

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    //-------------------------------------------------------------
}
